const express = require("express");

const router = express.Router();

const courseDB = require("../../schemas/course.js");

const upload = require("../../middle/multer/coverImage");
const path = require("path");

// 获取课程列表
router.get("/courseList", async (req, res) => {
  // 前端要 具体页数currentPage 具体的数据条数pageSize  筛选项:kindName(类别) courseName(课程)
  const { kindName, courseName, currentPage, pageSize } = req.query;
  let data = await courseDB.find();

  let kindNameOptions = data.map((item) => {
    return item.kindName;
  });
  // let a = [...new Set(kindNameOptions)];
  // console.log(a);
  kindNameOptions = kindNameOptions.filter((item, index) => {
    return kindNameOptions.indexOf(item) === index;
  });
  // console.log(kindNameOptions);

  // 筛选类别
  if (kindName) {
    data = data.filter((item) => {
      return item.kindName === kindName;
    });
  }
  // 筛选课程名
  if (courseName) {
    data = data.filter((item) => {
      return item.courseName.includes(courseName);
    });
  }

  // 按照更新事件倒序排列
  data.sort((a, b) => {
    return b.updateTime - a.updateTime;
  });

  // 总数
  const total = data.length;

  // 返回splice切下来的数组  currentPage2  pageSize5
  data = data.splice(pageSize * (currentPage - 1), pageSize);

  res.send({
    code: 0,
    data,
    total,
    kindNameOptions,
  });
});

// 修改课程基础信息
router.get("/reviseCourseBase", async (req, res) => {
  const { courseName, downPrice, originalPrice, sellingPrice } = req.body;

  courseDB
    .findOneAndUpdate(
      { courseName },
      { downPrice, originalPrice, sellingPrice }
    )
    .then(() => {
      // 修改成功
      res.send({
        code: 0,
        txt: "修改课程信息成功",
      });
    })
    .catch((err) => {
      // 修改不成功
      res.send({
        code: 1,
        txt: "修改课程信息失败",
      });
    });
});
// 修改课程封面信息
router.post("/reviseCourseCover", upload.single("file"), async (req, res) => {
  const { courseName, description } = req.body;
  console.log(req.file, req.body);

  if (description) {
    // 有描述
    courseDB.findOneAndUpdate({ courseName }, { description }).then(() => {});
  }

  if (req.file) {
    let coverImage = path.join("/images/coverImage", req.file.filename);
    // let coverImage = `/images/coverImage/${req.file.filename}`;

    courseDB.findOneAndUpdate({ courseName }, { coverImage }).then(() => {});
  }

  res.send({
    code: 0,
    txt: "修改封面信息成功",
  });
});

module.exports = router;
